package com.yang.singleton;

import java.util.Objects;

/**
 * 懒汉式 + 锁
 * 通过给getInstance()方法加锁，解决对象不唯一的问题，但是同时也带来效率下降的问题
 * */
public class Singleton4 {

    //构造方法私有化
    private Singleton4(){}

    private static Singleton4 INSTANCE;

    public static synchronized Singleton4 getInstance() {
        if (Objects.isNull(INSTANCE)) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new Singleton4();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                System.out.println(Singleton4.getInstance().hashCode());
            }).start();
        }
    }

}
